﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using BannerLib4Net.Core.Utilities.Configuration;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;

namespace BannerLib4Net.Build.Nant.Tasks
{
    [TaskName("SeleniumStart")]
    public class SeleniumStart: Task
    {

        ///<summary>
        ///Server Port
        ///</summary>
        [TaskAttribute("port", Required = false)]
        [Int32ValidatorAttribute(MinValue = 0, MaxValue = 60000)]
        public virtual Int32 Port { get; set; }

        ///<summary>
        ///Server Timeout
        ///</summary>
        [TaskAttribute("timeout", Required = false)]
        [Int32ValidatorAttribute(MinValue = 0, MaxValue = 60000)]
        public virtual Int32 Timeout { get; set; }

        /// <summary>
        /// Server Jar Location
        /// </summary>
        [BuildElement("FileSet", Required = true)]
        public virtual FileSet SeleniumFileSet { get; set; }


        protected override void ExecuteTask()
        {
            String javaHome = SettingsUtility.GetJavaInstallationPath();
            String javaExecutable = SettingsUtility.GetJavaExecutable();
            String javaPath = String.Empty;
            StringBuilder seleniumArguments = new StringBuilder();

            if(this.SeleniumFileSet.FileNames.Count > 0)
            {
                if(!String.IsNullOrEmpty(javaHome) && !String.IsNullOrEmpty(javaExecutable))
                {
                    javaPath = javaHome + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + javaExecutable;

                    if(Port != Int32.MinValue)
                    {
                        seleniumArguments.Append(String.Format("-port {0} ", Port)); 
                    }

                    if(Timeout != Int32.MinValue)
                    {
                        seleniumArguments.Append(String.Format("-timeout {0} ", Timeout));
                    }

                    seleniumArguments.Append(String.Format("-jar {0} ", SeleniumFileSet.FileNames[0]));

                    LogInfoMessage(String.Format("Using command: {0}", javaPath + " " + seleniumArguments.ToString()));

                    ProcessStartInfo info = new ProcessStartInfo(javaPath, seleniumArguments.ToString());

                    info.UseShellExecute = false;
                    info.CreateNoWindow = true;
                    info.RedirectStandardError = true;

                    try
                    {
                        Process.Start(info);
                    }
                    catch (Exception ex)
                    {
                        LogErrorMessage(ex.Message);                     
                    }
                    

                }
                else
                {
                    LogInfoMessage("Could not find a java home or java executable. Have you configured your JAVA_HOME environment variable?");
                }
            }
            else
            {
                LogInfoMessage("Could not start the Selenium Service, there are not files specified.");
            }

            
        }

        /// <summary>
        /// Logs an infomation message to the build
        /// </summary>
        /// <param name="Message">String representing the message to be logged</param>
        private void LogInfoMessage(String Message)
        {
            if (this.Verbose)
            {
                Log(Level.Info, Message);
            }
        }

        /// <summary>
        /// Logs an infomation message to the build
        /// </summary>
        /// <param name="Message">String representing the message to be logged</param>
        private void LogErrorMessage(String Message)
        {
            Log(Level.Error, Message);  
        }


    }
}
